import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'

export async function GET(
  request: NextRequest,
  { params }: { params: { userId: string } }
): Promise<NextResponse> {
  try {
    const { userId } = params
    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '12')
    const offset = (page - 1) * limit

    // 获取用户信息
    const user = await prisma.vms_user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        name: true,
        email: true,
      }
    })

    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      )
    }

    // 获取用户的公开课程总数
    const totalCourses = await prisma.vms_course.count({
      where: {
        user_id: userId,
        status: 'published'
      }
    })

    // 获取用户的公开课程列表
    const courses = await prisma.vms_course.findMany({
      where: {
        user_id: userId,
        status: 'published'
      },
      select: {
        id: true,
        title: true,
        description: true,
        cover_image: true,
        is_free: true,
        view_count: true,
        participant_count: true,
        access_token: true,
        created_at: true,
        updated_at: true,
        _count: {
          select: {
            sections: {
              where: {
                published: true
              }
            }
          }
        }
      },
      orderBy: {
        created_at: 'desc'
      },
      skip: offset,
      take: limit
    })

    const totalPages = Math.ceil(totalCourses / limit)

    return NextResponse.json({
      user,
      courses: courses.map(course => ({
        ...course,
        sectionCount: course._count.sections
      })),
      pagination: {
        page,
        limit,
        total: totalCourses,
        totalPages,
        hasNext: page < totalPages,
        hasPrev: page > 1
      }
    })
  } catch (error) {
    console.error('Error fetching user courses:', error)
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    )
  }
}